package com.zh.mp.demo.response;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

//控制器通知
@ControllerAdvice(
        // 指定拦截包的控制器
        basePackages = { "com.zh.mp.demo.modules.demo.controller.*" },
        // 限定被标注为@Controller或者@RestController的类才被拦截
        annotations = { Controller.class, RestController.class }
)
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        String requestPath = request.getURI().getPath();
        /*if (!requestPath.startsWith("/canal/park")) {
            return body;
        }*/

        if (body instanceof Result) {
            return body;
        }

        if (body instanceof String) {
            return body;
        }

        return new Result(body);
    }
}
